package com.valuegroup.smarttodo.ui.programme.ideality;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.vo.AppCustomCfg;
import com.valuegroup.smarttodo.data.vo.IdealityItemVo;
import com.valuegroup.smarttodo.util.Cfg;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 理想首页
 */
public class IdealityFragment extends Fragment {


    @BindView(R.id.recycler_ideality_list)
    RecyclerView recyclerView;

    private IdealityAdapter adapter;
    private Unbinder unbinder;
    private AppCustomCfg cfg;
    private boolean initFinish;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ideality, container, false);
        unbinder = ButterKnife.bind(this, view);
        cfg = Cfg.getCfg(getContext());
        initFinish = true;

        assert recyclerView != null;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new IdealityAdapter(getContext(), loadData());
        recyclerView.setAdapter(adapter);
        setHasOptionsMenu(true);
        return view;
    }

    private List<IdealityItemVo> loadData() {
        return ServiceFactory.getInstance().getIdealityService().findList(cfg.isIdealityHideFinish());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static IdealityFragment newInstance() {
        return new IdealityFragment();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //先clear()一下, 这样按钮就只有Fragment中设置的自己的了, 不会有Activity中的按钮.
        menu.clear();
        inflater.inflate(R.menu.menu_ideality, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.menu_ideality_2).setTitle(!cfg.isIdealityHideFinish() ? R.string.ideality_m2 : R.string.ideality_m2_o);

        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.menu_ideality_1:
                startActivityForResult(new Intent(getContext(), IdealityActivity.class), 1003);
                break;
            case R.id.menu_ideality_2:
                // 隐藏已完成项
                cfg.setIdealityHideFinish(!cfg.isIdealityHideFinish());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
        }
        return true;
    }

    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData();
    }

    class IdealityAdapter extends CommonRecyclerAdapter<IdealityItemVo> {

        public IdealityAdapter(Context context, List<IdealityItemVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_ideality_card);
            setBottomLayoutId(R.layout.item_default_bottom);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {

            IdealityItemVo data = getData(position);

            v.getView(R.id.layoutRoot).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getmContext(), IdealityActivity.class);
                    intent.putExtra(IdealityActivity.PARAMS_KEY, data.getId());
                    intent.putExtra(IdealityActivity.PARAMS_POSITION, position);
                    startActivityForResult(intent, 1003);
                }
            });

            v.setText(R.id.labTitle, data.getLabTitle());
            //v.setText(R.id.labBranch, data.getLabBranch());
            v.setText(R.id.labDate, "更新于" + data.getLabDate());


            // 成长值与完成状态
            v.setViewVisibility(R.id.tagFinish, data.isShowFinish());
            v.setViewVisibility(R.id.tagGrow, !data.isShowFinish());
            if (!data.isShowFinish()) {
                v.setImageResource(R.id.labOrientation, data.isShowGrowDown() ? R.drawable.ic_down_green : R.drawable.ic_up_red);
                v.setText(R.id.labGrow, String.valueOf(data.getLabGrow()));
            }

            ImageView imgCover = v.getView(R.id.imgCover);

            // 设置封面图片
            if (!TextUtils.isEmpty(data.getCoverPath())) {
                //Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
                //imgCover.setImageURI(u);

                // 设置圆角图片
                // RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.ideality_piano));
            /*RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(), DATA.getCoverPath());
            roundedBitmapDrawable1.setCornerRadius(6);
            imgCover.setImageDrawable(roundedBitmapDrawable1);*/

                RequestOptions options = RequestOptions
                        .bitmapTransform(new RoundedCorners(6)) //设置图片圆角角度
                        .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                        .skipMemoryCache(true)//不做内存缓存
                        .placeholder(R.drawable.ic_default_image)//图片加载出来前，显示的图片
                        .fallback(R.drawable.ic_default_image) //url为空的时候,显示的图片
                        .error(R.drawable.ic_default_image);//图片加载失败后，显示的图片

                Uri u = new Uri.Builder().scheme("file").path("//" + data.getCoverPath()).build();
                Glide.with(IdealityFragment.this).load(u)
                        .apply(options)
                        .into(imgCover);
            }

        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }
    }

}
